#ifndef _M_HTTP_H__
#define _M_HTTP_H__

#include "../server/muduo_server.hpp"
#include <fstream>
#include <regex>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

std::unordered_map<int, std::string> _statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

class Util
{
public:
    /**
     * 字符串分割函数
     * src表示待分割的字符串
     * sep表示分割的标识符
     * arry表示将分割后的字串放到arry中
    */
    static size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *arry)
    {
        size_t offset = 0;
        while(offset < src.size())
        {
            size_t pos = src.find(sep,offset);
            //一定是最后一个sep,那么后面要么是空的要么都是字串
            if(pos == std::string::npos)
            {
                //判断后面是空的
                if(pos == src.size()) break;
                //后序都是字串,直接添加进行返回
                arry->push_back(src.substr(offset));
                return arry->size();
            }
            //表示的是有多个sep连续出现
            if(pos == offset)
            {
                offset = pos + sep.size();
                continue;
            }
            //正常的将字串添加到arry中
            arry->push_back(src.substr(offset,pos - offset));
            offset = pos + sep.size();
        }
        return arry->size();
    }
    /**
     * 文件的读取
     * filename表示待读取的文件名称
     * buf表示将读取的内容存放到哪个Buffer缓冲区中
    */
    static bool ReadFile(const std::string& filename,std::string* buf)
    {
        std::ifstream ifs(filename,std::ios::binary);
        if(false == ifs.is_open())
        {
            ERR_LOG("open %s file failed!",filename.c_str());
            return false;
        }
        size_t fsize = 0;
        ifs.seekg(0,ifs.end);//跳转读写位置到文件末尾
        fsize = ifs.tellg();//获取当前读写位置相对于起始位置的偏移量,从末尾偏移刚好是文件大小
        ifs.seekg(0,ifs.beg);//跳转到文件起始位置
        buf->resize(fsize);//开辟文件大小的空间
        ifs.read(&(*buf)[0],fsize);
        if(false == ifs.good())
        {
            ERR_LOG("read %s file failed",filename.c_str());
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }
    /**
     * 文件的写入
     * filename表示将内容写入的文件
     * buf表示带写入的内容
    */
    static bool WriteFile(const std::string& filename,const std::string& buf)
    {
        std::ofstream ofs(filename,std::ios::binary | std::ios::trunc);
        if(false == ofs.is_open())
        {
            ERR_LOG("open %s file failed!",filename.c_str());
            return false;
        }
        ofs.write(buf.c_str(),buf.size());
        if(false == ofs.good())
        {
            ERR_LOG("write %s file failed",filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }
    /**
     * 将url进行编码
     * url表示的待编码的串
     * start_w3c表示是否启用w3c标准
     * 编码格式:将特殊字符的ascii值转换为16进制字符,前缀%，C++->C%2B%2B
     * RFC3986中规定 . - _ ~ 和数字不进行编码
     * w3c规定,查询字符串中的空格,需要编码为+, 解码则是+转换为空格
     * isalnum(int num)表示判断并返回num是否属于0~9的数字
    */
    static std::string UrlEncode(const std::string& url,bool start_w3c)
    {
        std::string res;
        for(auto &c : url)
        {
            if(c == '.' || c == '_' || c == '-' || c == '~' || isalnum(c))
            {
                res += c;
                continue;;
            }
            if(c == ' ' && start_w3c == true)
            {
                res += '+';
                continue;
            }
            char tmp[4] = {0};
            snprintf(tmp,4,"%%%02X",c);
            res += tmp;
        }
        return res;
    }
    static char HEXTIO(char c)
    {
        if(c >= '0' && c <= '9')
            return c - '0';
        else if(c >= 'a' && c <= 'z')
            return c - 'a' + 10;
        else if(c >= 'A' && c <= 'Z')
            return c - 'A' + 10;
        return -1;
    }
    /**
     * url的解码
     * url表示待解码的字符串
     * start_w3c表示是否启用w3c规则 也就是解码时将'+' 转换成 ' '
     * 遇到了%,则取出后两位进行转化,第一个字符左移2位再加上第二位(因为是16进制)
    */
    static std::string UrlDeCode(const std::string& url,bool start_w3c)
    {
        std::string res;
        for(int i = 0; i < url.size(); i++)
        {
            if(url[i] == '+' && start_w3c == true)
            {
                res += ' ';
                continue;
            }
            if(url[i] == '%' && i + 2 < url.size())
            {
                char v1 = HEXTIO(url[i+1]);
                char v2 = HEXTIO(url[i+2]);
                char v = v1 * 16 + v2;
                res += v;
                i += 2;
                continue;
            }
            res += url[i];
        }
        return res;
    }

    //响应状态码的描述信息获取
    static std::string StatuDesc(int x)
    {
        auto it = _statu_msg.find(x);
        if(it == _statu_msg.end())
            return "Unknow";
        return it->second;
    }

    //获取文件后缀
    static std::string ExtMime(const std::string &filename)
    {
        size_t pos = filename.find_last_of('.');
        if(pos == std::string::npos)
            return "applocation/occet-stream";
        std::string exit = filename.substr(pos);
        auto it = _mime_msg.find(exit);
        if(it == _mime_msg.end())
            return "applocation/occet-stream";
        return it->second;
    }

    //判断该文件是否是一个目录文件
    static bool IsDirectory(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(),&st);
        if(ret < 0)
            return false;
        return S_ISDIR(st.st_mode);
    }

    //判读该文件是否是一个普通文件
    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(),&st);
        if(ret < 0)
            return false;
        return S_ISREG(st.st_mode);
    }

    //有效路径的判断
    static bool ValidPath(const std::string& path)
    {
        std::vector<std::string> subdir;
        int level = 0;
        Split(path,"/",&subdir);
        for(auto& dir : subdir)
        {
            if(dir == "..")
            {
                level--;
                if(level < 0) return false;
                continue;
            }
            level++;
        }
        return true;
    }
};

class HttpRequest
{
public: 
    HttpRequest():_version("HTTP/1.1") {}
    //插入头部字段
    void SetHeader(const std::string& key,const std::string& val)
    {
        _headers.insert(std::make_pair(key,val));
    }
    //判断是否存在指定头部字段
    bool HasHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
            return false;
        return true;
    }
    //获取头部字段中的内容
    std::string GetHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
            return "";
        return it->second;
    }
    //插入查询字符串
    void SetParam(const std::string& key,const std::string& val)
    {
        _params.insert(std::make_pair(key,val));
    }
    ////判断是否存在指定查询字符串
    bool HasParams(const std::string& key)
    {
        auto it = _params.find(key);
        if(it == _params.end())
            return false;
        return true;
    }
    //获取查询字符串内容
    std::string GetParam(const std::string& key)
    {
        auto it = _params.find(key);
        if(it == _params.end())
            return "";
        return it->second;
    }
    //获取正文长度
    size_t ContentLength()
    {
        bool ret = HasHeader("Content-Length");
        if(ret == false)
            return 0;
        std::string clen = GetHeader("Content-Length");
        return std::stol(clen);
    }
    //判断是否是短连接
    bool Close() const
    {
        //没有Connection字段,或者有Connection但是值是close,则是短连接,否则就是长连接
        // DBG_LOG("%d",HasHeader("Connection") == true);
        // DBG_LOG("%d",GetHeader("Connection") == "keep-alive");
        if(HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
    //重置接口
    void Reset()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch match;
        _matches.swap(match);
        _headers.clear();
        _params.clear();
    }
public:
    std::string _method; //请求方法
    std::string _path;   //资源路径
    std::string _version;//协议版本
    std::string _body;   //请求正文
    std::smatch _matches;//资源路径提取数据
    std::unordered_map<std::string, std::string> _headers;//头部字段
    std::unordered_map<std::string, std::string> _params;//查询字符串
};

class HttpResponse
{
public:
    HttpResponse()
    :_statu(200),_redirect_flag(false)
    {}
    HttpResponse(int statu)
    :_statu(statu),_redirect_flag(false)
    {}
    //插入头部字段
    void SetHeader(const std::string& key,const std::string& val)
    {
        _headers.insert(std::make_pair(key,val));
    }
    //判断是否存在指定头部字段
    bool HasHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
            return false;
        return true;
    }
    //获取头部字段中的内容
    std::string GetHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
            return "";
        return it->second;
    }
    //设置正文字段
    void SetContent(const std::string& body, const std::string& type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type",type); 
    }
    //重定向设置
    void SetRedirect(const std::string& url,int statu = 302)
    {
        _statu = statu;
        _redirect_flag = true;
        _redirect_url = url;
    }
    //长短连接的判断
    bool Close()
    {
        //没有Connection字段,或者有Connection但是值是close,则是短连接,否则就是长连接
        // DBG_LOG("%d",HasHeader("Connection") == true);
        // DBG_LOG("%d",GetHeader("Connection") == "keep-alive");
        // DBG_LOG("%s",GetHeader("Connection").c_str());
        if(HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
    //重置接口
    void Rest()
    {
        _statu = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
public:
    int _statu;           //状态码
    bool _redirect_flag;  //重定向设置
    std::string _body;    //正文
    std::string _redirect_url;//重定向的url
    std::unordered_map<std::string, std::string> _headers;//头部字段信息
};


typedef enum{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatu;
#define MAX_LINE 8192
class HttpContext
{
public:
    HttpContext()
    :_resp_statu(200),_recv_statu(RECV_HTTP_LINE)
    {}
    //获取当前响应状态码
    int RespStatu() { return _resp_statu; }
    //获取当前接收状态
    HttpRecvStatu RecvStatu() { return _recv_statu; }
    //获取已经接收到的请求信息
    HttpRequest& Request() { return _request; } 
    //获取当前请求
    void RecvHttpRequest(Buffer* buff)
    {
        //不同的状态，做不同的事情，但是这里不要break
        //因为处理完请求行后，应该立即处理头部，而不是退出等新数据
        switch(_recv_statu) 
        {
            case RECV_HTTP_LINE: RecvHttpLine(buff);
            case RECV_HTTP_HEAD: RecvHttpHead(buff);
            case RECV_HTTP_BODY: RecvHttpBody(buff);
        }
        return;
    }
    //重置接口
    void Reset()
    {
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;
        _request.Reset();
    }
private:
    //请求行中的查询字符串设置
    bool ParseHttpLine(const std::string& line)
    {
        std::smatch matches;
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
        bool ret = std::regex_match(line, matches, e);
        if (ret == false) {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;//BAD REQUEST
            return false;
        }
        //0 : GET /bitejiuyeke/login?user=xiaoming&pass=123123 HTTP/1.1
        //1 : GET
        //2 : /bitejiuyeke/login
        //3 : user=xiaoming&pass=123123
        //4 : HTTP/1.1

        //1.请求方法的获取
        _request._method = matches[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        //2.获取资源路径,需要进行url的解码操作,但是不需要+转空格,因为此时不是查询操作
        _request._path = Util::UrlDeCode(matches[2],false);
        //3.获取协议版本
        _request._version = matches[4];
        //4.获取查询字符串和相应的处理
        //  格式 key=val&key=val....., 先以 & 符号进行分割，得到各个字串
        std::string str = matches[3];
        std::vector<std::string> arry;
        Util::Split(str,"&",&arry);
        for(auto &s : arry)
        {
            //针对各个字串,以=符号进行分割,得到key和val
            size_t pos = s.find("=");
            if(pos == std::string::npos)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400;//BAD REQUEST
                return false;
            }
            //因为此时是对查询字符串的处理,所以需要将+转化成空格
            std::string key = Util::UrlDeCode(s.substr(0,pos),true);
            std::string val = Util::UrlDeCode(s.substr(pos + 1),true);
            _request.SetParam(key,val);
        }
        return true;
    }
    //获取一行信息
    bool RecvHttpLine(Buffer* buff)
    {
        if(_recv_statu != RECV_HTTP_LINE) return false;
        //1.先拿到一行数据
        std::string line = buff->GetLineAndPop();
        //2.判断该数据是否符合我们的要求
        //2.1拿到的数据是不是空的
        if(line.size() == 0)
        {
            //缓冲区中的数据不足一行.需要判断缓冲区中可读数据的长度,如果很长都不足一行,说明该数据存在问题
            if(buff->ReadAblesSize() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;//URI TOO LONG
                return false;
            }
            //缓冲区中不足一行,直接返回,让其继续读取
            return true;
        }
        //2.2判断读取的数据是否超过了我们一行的限定
        if(line.size() > MAX_LINE)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414;//URI TOO LONG
            return false;
        }
        //走到这里就表示获取到了一行正确的数据
        bool ret = ParseHttpLine(line);
        if(ret == false)
            return false;
        //首行处理完毕，进入头部获取阶段
        _recv_statu = RECV_HTTP_HEAD;
        return true;
    }
    //接收头部字段
    bool RecvHttpHead(Buffer *buff)
    {
        if(_recv_statu != RECV_HTTP_HEAD) return false;
        //一行一行的获取,直到遇到了\r\n \n为止
        //头部的格式 key: val\r\nkey: val\r\n....
        while(1)
        {
            std::string line = buff->GetLineAndPop();
            //和RecvHttpLine一样的判断手法
            if(line.size() == 0)
            {
                if(buff->ReadAblesSize() > MAX_LINE)
                {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414;//URI TOO LONG
                    return false;
                }
                //不足一行数据,让其继续获取
                return true;
            }
            if(line.size() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;//URI TOO LONG
                return false;
            }
            //因为是while获取的，必须遇到\n或者\r\n
            if(line == "\n" || line == "\r\n") break;
            //到这就获取到了一行数据了
            bool ret= ParseHttpHead(line);
            if(ret == false)
                return false;
        }
        //头部字段处理完毕,进入正文阶段
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }
    bool ParseHttpHead(std::string& line)
    {
        //key: val\r\nkey: val\r\n....
        if (line.back() == '\n') line.pop_back();//末尾是换行则去掉换行字符
        if (line.back() == '\r') line.pop_back();//末尾是回车则去掉回车字符
        size_t pos = line.find(": ");
        if(pos == std::string::npos)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;//Bad Request
            return false;
        }
        std::string key = line.substr(0,pos);
        std::string val = line.substr(pos + 2);
        _request.SetHeader(key,val);
        return true;
    }
    //接收正文部分
    bool RecvHttpBody(Buffer* buff)
    { 
        if(_recv_statu != RECV_HTTP_BODY) return false;
        //1.获取到正文的长度
        size_t content_length = _request.ContentLength();
        if(content_length == 0)
        {
            //没有正文，则请求接收解析完毕
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        //2.获取本次的正文长度
        //此次获取到的正文长度需要减去body中原有的数据长度
        size_t len = content_length - _request._body.size();
        //3.将获取到的正文放到body中
        if(buff->ReadAblesSize() >= len)
        {
            //把可读的内容追加到原有的正文后面
            _request._body.append(buff->ReadPosition(),len);
            buff->MoveReadOffset(len);
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        //4.如果缓冲区中没有数据,无法满足当前的正文需要,数据不足,把数据取出,然后等新数据的到来
        _request._body.append(buff->ReadPosition(),buff->ReadAblesSize());
        buff->MoveReadOffset(buff->ReadAblesSize());
        return true;
    }
private:
    int _resp_statu;              //响应状态码
    HttpRecvStatu _recv_statu;    //当前接收状态
    HttpRequest _request;         //已经获取到的请求信息
};

#define DEFALT_TIMEOUT 10
// using Handler = std::function<void(const HttpRequest&,HttpResponse*)>;
// using Handlers = std::vector<std::pair<std::regex, Handler>>;//路由表
using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
using Handlers = std::vector<std::pair<std::regex, Handler>>;
class HttpServer
{
public:
    HttpServer(int port,int timeout = DEFALT_TIMEOUT):_server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected,this,std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage,this,std::placeholders::_1,std::placeholders::_2));
    }
    void SetBaseDir(const std::string& path)
    {
        assert(Util::IsDirectory(path) ==true);
        _basedir = path;
    }
    /*设置/添加，请求（请求的正则表达）与处理函数的映射关系*/
    void Get(const std::string& path,const Handler& handler)
    {
        _get_route.push_back(std::make_pair(std::regex(path),handler));
    }
    void Post(const std::string& path, const Handler& handler)
    {
        _post_route.push_back(std::make_pair(std::regex(path),handler));
    }
    void Put(const std::string& path, const Handler& handler)
    {
        _put_route.push_back(std::make_pair(std::regex(path),handler));
    }
    void Delete(const std::string& path,const Handler& handler)
    {
        _delete_route.push_back(std::make_pair(std::regex(path),handler));
    }
    void SetThreadCount(int count)
    {
        _server.SetThreadCount(count);
    }
    void Listen()
    {
        _server.Start();
    }
private:
    //返回一个网页的错误提示
    void ErrorHandler(const HttpRequest &req, HttpResponse *resp)
    {
        //1. 组织一个错误展示页面
            std::string body;
            body += "<html>";
            body += "<head>";
            body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
            body += "</head>";
            body += "<body>";
            body += "<h1>";
            body += std::to_string(resp->_statu);
            body += " ";
            body += Util::StatuDesc(resp->_statu);
            body += "</h1>";
            body += "</body>";
            body += "</html>";
            //2. 将页面数据，当作响应正文，放入rsp中
            resp->SetContent(body, "text/html");
    }
    //将httpresponse中的要素按照http协议格式进行组织发送
    void WriteResponse(const PtrConnection& conn,const HttpRequest &req, HttpResponse &resp)
    {
        //1.完善头部字段
        if(req.Close() == true)
            resp.SetHeader("Connection", "close");
        else 
            resp.SetHeader("Connection", "keep-alive");
        //正文
        if(resp._body.empty() == false && resp.HasHeader("Content-Length") == false)
            resp.SetHeader("Content-Length",std::to_string(resp._body.size()));
        if(resp._body.empty() == false && resp.HasHeader("Content-Type") == false)
            resp.SetHeader("Content-Type","application/octet-stream");//字节流
        //重定向设置
        if(resp._redirect_flag == true)
            resp.SetHeader("Location",resp._redirect_url);
        //2.把resp中的元素,按照http协议格式进行组织
        std::stringstream resp_str;
        resp_str << req._version << " " << std::to_string(resp._statu) << " " << Util::StatuDesc(resp._statu) << "\r\n";
        for(auto &head : resp._headers)
        {
            resp_str << head.first << ": " << head.second << "\r\n";
        }
        resp_str << "\r\n";
        resp_str << resp._body;
        //3.发送数据
        conn->Send(resp_str.str().c_str(), resp_str.str().size());
    }
    bool IsFileHandler(const HttpRequest &req)
    {
        //要先有静态资源的根目录
        if(_basedir.empty()) 
            return false;
        //请求方法必须是GET || HEAD
        if(req._method != "GET" || req._method != "HEAD")
            return false;
        //判断他的路径是否合法
        if(Util::ValidPath(req._path) == false)
            return false;
        //请求的资源必须存在,且是一个普通文件
        //有一种请求比较特殊 -- 目录：/, /image/， 这种情况给后边默认追加一个 index.html
        //index.html    /image/a.png
        //不要忘了前缀的相对根目录,也就是将请求路径转换为实际存在的路径  /image/a.png  ->   ./wwwroot/image/a.png
        std::string req_path = _basedir + req._path;
        if(req_path.back() == '/')
            req_path += "index.html";
        if(Util::IsRegular(req_path) == false)
            return false;
        return true;
    }
    //获取静态资源路径
    void FileHandler(const HttpRequest &req, HttpResponse *resp)
    {
        //先拿到实际的路径
        std::string req_path = _basedir + req._path;
        if(req_path.back() == '/')
            req_path += "index.html";
        bool ret = Util::ReadFile(req_path,&resp->_body);
        if(ret == false)
            return;
        std::string mime = Util::ExtMime(req_path);
        resp->SetHeader("Content-Type", mime);
        return;
    }
    //功能性请求的获取
    void Dispatcher(HttpRequest &req, HttpResponse *resp, Handlers &handlers)
    {
        //在对应请求方法的路由表中，查找是否含有对应资源请求的处理函数，有则调用，没有则发挥404
        //思想：路由表存储的时键值对 -- 正则表达式 & 处理函数
        //使用正则表达式，对请求的资源路径进行正则匹配，匹配成功就使用对应函数进行处理
        //  /numbers/(\d+)       /numbers/12345
        for(auto &handler : handlers)
        {
            const std::regex &re = handler.first;
            const Handler &functor = handler.second;
            bool ret = std::regex_match(req._path,req._matches,re);
            if(ret == false)
                continue;
            return functor(req,resp);
        }
        resp->_statu = 404;
    }
    //设置上下文
    void OnConnected(const PtrConnection& conn)
    {
        conn->SetContext(HttpContext());
        DBG_LOG("new connection:%p",conn.get());
    }
    //路由的请求
    void Route(HttpRequest &req, HttpResponse *resp)
    {
        //需要对请求进行分辨,是一个静态资源请求,还是一个功能性请求
        //静态资源请求,就进行静态资源请求的处理
        if(IsFileHandler(req) == true)
            return FileHandler(req,resp);
        //功能性请求, 就需要分辨是哪种类型的请求
        if(req._method == "GET" || req._method == "HEAD")
            return Dispatcher(req, resp, _get_route);
        else if (req._method == "POST") 
            return Dispatcher(req, resp, _post_route);
        else if (req._method == "PUT") 
            return Dispatcher(req, resp, _put_route);
        else if (req._method == "DELETE") 
            return Dispatcher(req, resp, _delete_route);
        //如果这两种请求都不属于,也没有对应的请求处理函数,那就返回405
        resp->_statu = 405;// Method Not Allowed
        return ;
    }
    //缓冲区数据解析和处理
    void OnMessage(const PtrConnection& conn,Buffer* buff)
    {
        while(buff->ReadAblesSize() > 0)
        {
            //1.获取上下文
            HttpContext* context = conn->GetContext()->get<HttpContext>();
            //2.对获取到的数据进行处理,得到一个Request对象
            //1.如果缓冲区中的数据解析出错,直接返回出错响应
            //2.解析正常,且请求已经获取完毕,进行处理
            context->RecvHttpRequest(buff);
            HttpRequest& req = context->Request();
            HttpResponse resp(context->RespStatu());
            if(context->RespStatu() >= 400)
            {
                //出错
                //填充一个错误显示页面数据到rsp中
                ErrorHandler(req,&resp);
                //组织响应发送给客户端
                WriteResponse(conn,req,resp);
                context->Reset();
                //出错了就把缓冲区数据清空
                buff->MoveReadOffset(buff->ReadAblesSize());
                //关闭连接
                conn->ShutDown();
                return;
            }
            if(context->RecvStatu() != RECV_HTTP_OVER)
                return;
            //3.请求路由+业务处理
            Route(req,&resp);
            //4.对Request封装成Response进行发送
            WriteResponse(conn,req,resp);
            //5.重置上下文
            context->Reset();
            //6.判断长短连接进行对应的释放操作
            if(resp.Close() == true)
                conn->ShutDown();
        }
        
    }
private:
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir;
    TcpServer _server;
};

#endif